//
//  MainViewController.swift
//  Weibo01
//
//  Created by mac on 16/3/19.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    // MARK:监听方法
    @objc private func clickComposedButton () {
    
    }
    
    
    // MARK: - 视图的生命周期
    override func viewDidLoad() {
        super.viewDidLoad()

       //添加控制器，并不会创建tarbar中的按钮，而是懒加载的什么时候用，什么时候加载
        addChildViewControllers()
        
//        print(tabBar.subviews)
        
        setupComposedButton()
    }
   
    override func viewWillAppear(animated: Bool) {
        //会创建tarbar中所有的子控件
        super.viewWillAppear(animated)
        
//        print(tabBar.subviews)
        
        //将控件移到最上面
        tabBar.bringSubviewToFront(composedButton)
    }
    
    private lazy var composedButton: UIButton = UIButton (
        imageName: "tabbar_compose_icon_add",
        backGroudImage: "tabbar_compose_button")

}

// MARK: - 设置界面
extension MainViewController {
//   视图控制器添加在Navigation中Navigation又添加在TabBar上

    private func setupComposedButton(){
        
        tabBar.addSubview(composedButton)
        
        //设置按钮的frame
        let count = childViewControllers.count
        let w = tabBar.frame.width / CGFloat(count)
        
        //将其
        composedButton.frame = CGRectInset(tabBar.bounds, 2*w, 0)
        
        
    }
    
    private func addChildViewControllers() {
         //一次性设置选中的颜色,因为是bar控制器,就不用设置选中图片了
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "手页", inmageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", inmageName: "tabbar_message_center")
        
        //添加一个中间按钮
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", inmageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", inmageName: "tabbar_profile")
}
    private func addChildViewController(vc:UIViewController,title:String,inmageName:String) {
        
        //设置标题，是由内往外的
        vc.title = title
        //设置图片
        vc.tabBarItem.image = UIImage(named: inmageName)
        //设置导航控制器
        let nav = UINavigationController(rootViewController: vc)
        
        //单独的设置bar的标题
//        nav.tabBarItem.title = "首页"
        
        //将创建的子控制器添加到福控制器中
        addChildViewController(nav)

    }
}